package com.cj.controller;

import com.cj.pojo.Article;
import com.cj.pojo.PageBean;
import com.cj.pojo.Result;
import com.cj.service.ArticleService;
import com.cj.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;


@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @PostMapping("/add")
    public Result add(@RequestBody @Validated Article article) {
        articleService.add(article);
        return Result.success();
    }

    @GetMapping("/list")
    public Result<PageBean<Article>> list(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String state
    ) {
        PageBean<Article> pb =  articleService.list(pageNum,pageSize,categoryId,state);
        return Result.success(pb);
    }
    @GetMapping("/all")
    public Result<List<Article>> findAll() {
        List<Article> articles = articleService.findAll();
        return Result.success(articles);
    }
    @DeleteMapping("/{id}")
    public ResponseEntity<Result> delete(@PathVariable("id") Integer id) {
        articleService.delete(id);
        return ResponseEntity.ok(Result.success("删除成功"));
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated Article article) {
        articleService.update(article);
        return Result.success();
    }
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws Exception {
        //把文件的内容存储到本地磁盘上
        String originalFilename = file.getOriginalFilename();
        //保证文件的名字是唯一的,从而防止文件覆盖
        String filename = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
//        String url="E:\\home\\teach\\"+filename;
//        file.transferTo(new File(url));

        String url = AliOssUtil.uploadFile(filename,file.getInputStream());
        return Result.success(url);
    }
}
